package com.naiterui.ehp.bs.weixin.controller;

import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bs.weixin.exception.WeixinException;
import com.naiterui.ehp.bs.weixin.security.bean.JwtUser;
import com.naiterui.ehp.bs.weixin.security.util.JwtUserUtil;
import com.naiterui.ehp.bs.weixin.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = SwaggerTag.WEIXIN + SwaggerTag.USER_INFO)
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("user")
public class UserController {

    private final UserService userService;

    @ApiOperation("用户手机验证码发送")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "string", paramType = "path") })
    @GetMapping(value = "code/{phone}")
    public void smsCode(@PathVariable String phone) throws WeixinException {
        log.info("小程序用户注册绑定发送手机验证码 phone={}", phone);
        JwtUser jwtUser = JwtUserUtil.getJwtUser();
        userService.sendCode(jwtUser.getUserId(), phone);
    }

    @ApiOperation("用户手机校验绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "string", paramType = "path")
    })
    @PostMapping(value = "code/{phone}/{code}")
    public void smsCode(@PathVariable String phone, @PathVariable String code) throws WeixinException {
        log.info("用户手机校验绑定 phone={},code={}", phone, code);
        JwtUser jwtUser = JwtUserUtil.getJwtUser();
        userService.varifyCode(jwtUser.getUserId(), phone, code);
    }

    @ApiOperation("校验token，返回userId")
    @PostMapping("verify/token")
    public Long verifyToken(@RequestHeader("Authorization") String token) throws WeixinException {
        log.info("verify token token:{} ",token);
        JwtUser jwtUser = JwtUserUtil.getJwtUser();
        return jwtUser.getUserId();
    }
}
